package com.example.yichuangyun.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import androidx.annotation.NonNull;

import com.example.yichuangyun.R;
import com.example.yichuangyun.databinding.DialogPlayRecordBinding;
import com.example.yichuangyun.model.business.CallRecordDataModel;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.DateUtil;
import com.example.yichuangyun.utils.ToastHelper;

import java.io.IOException;
import java.lang.ref.WeakReference;

/**
 * 录音播放
 */
public class PlayRecordDialog {
    private Dialog dialog;
    private DialogPlayRecordBinding binding;
    private MediaPlayer mediaPlayer;
    private MyHandler handler;
    private final CallRecordDataModel.CallListModel.CallRecordModel callRecordModel;
    private final String linkedId;

    public PlayRecordDialog(Activity activity, CallRecordDataModel.CallListModel.CallRecordModel callRecordModel, String linkedId) {
        this.callRecordModel = callRecordModel;
        this.linkedId = linkedId;
        if (dialog == null) {
            getDialog(activity);
        }
    }

    private void getDialog(Activity activity) {
        handler = new MyHandler(this);
        binding = DialogPlayRecordBinding.inflate(LayoutInflater.from(activity));
        dialog = new Dialog(activity, R.style.prompt_progress_dialog_dimenabled);
        dialog.setContentView(binding.getRoot(), new LinearLayout.LayoutParams
                (LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        dialog.setCancelable(false);
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM);
        dialogWindow.setWindowAnimations(R.style.main_menu_animStyle);
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        dialogWindow.setAttributes(lp);
        binding.ivClose.setOnClickListener(v -> dismissDialog());

        binding.tvTitle.setText(String.format(activity.getString(R.string.user_sound_recording),
                TextUtils.isEmpty(callRecordModel.getUserName()) ? callRecordModel.getTelNumber() : callRecordModel.getUserName()));
        binding.tvDate.setText(DateUtil.getYearMonthDayHM(callRecordModel.getTrackTime()));
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(linkedId);
            mediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
        binding.ivPlay.setOnClickListener(v -> {
            if (CommonUtil.isCanClick()) {
                if (mediaPlayer.isPlaying()) {
                    binding.ivPlay.setImageResource(R.mipmap.icon_play_record);
                    mediaPlayer.pause();
                } else {
                    if (!binding.tvTotal.getText().toString().equals("00:00")) {
                        binding.ivPlay.setImageResource(R.mipmap.icon_pause_record);
                        mediaPlayer.start();
                        handler.sendEmptyMessage(1);
                    } else {
                        ToastHelper.show(activity.getString(R.string.user_sound_recording_damage));
                    }
                }
            }
        });
        setListener();
    }

    @SuppressLint("SetTextI18n")
    private void setListener() {
        mediaPlayer.setOnPreparedListener(mp -> {
            mediaPlayer.setLooping(false);
            int duration = mediaPlayer.getDuration();
            binding.tvTotal.setText(DateUtil.getTimeBySecond(duration / 1000));
            binding.tvLastTime.setText(DateUtil.getTimeBySecond(duration / 1000));
            binding.seekBar.setMax(duration);
            handler.sendEmptyMessage(1);
        });
        mediaPlayer.setOnCompletionListener(mp -> {
            binding.ivPlay.setImageResource(R.mipmap.icon_play_record);
            binding.tvPlayTime.setText("00:00");
            binding.tvLastTime.setText(DateUtil.getTimeBySecond((int) mediaPlayer.getDuration() / 1000));
            binding.seekBar.setProgress(0);
            handler.removeCallbacksAndMessages(null);
        });

        binding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mediaPlayer.seekTo(seekBar.getProgress());
            }
        });
    }

    public void showDialog() {
        dialog.show();
    }

    public void dismissDialog() {
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
        destroyResource();
    }

    public void destroyResource() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        handler.removeCallbacksAndMessages(null);
    }

    private static class MyHandler extends Handler {

        WeakReference<PlayRecordDialog> mDialog;

        public MyHandler(PlayRecordDialog dialog) {
            super();
            mDialog = new WeakReference<>(dialog);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            PlayRecordDialog dialog = mDialog.get();
            if (dialog.mediaPlayer != null) {
                dialog.binding.seekBar.setProgress(dialog.mediaPlayer.getCurrentPosition());
                dialog.binding.tvLastTime.setText("-" + DateUtil.getTimeBySecond((dialog.mediaPlayer.getDuration() - dialog.mediaPlayer.getCurrentPosition()) / 1000));
                dialog.binding.tvPlayTime.setText(DateUtil.getTimeBySecond(dialog.mediaPlayer.getCurrentPosition() / 1000));
                if (dialog.mediaPlayer.getCurrentPosition() < dialog.mediaPlayer.getDuration()) {
                    dialog.handler.sendEmptyMessageDelayed(1, 1000);
                }
            }
        }
    }
}
